package com.woniu.aiclient.tools;

import com.woniu.aiclient.config.RestClientApi;
import com.woniu.internalcommon.dto.POIType;
import com.woniu.internalcommon.dto.ResponseResult;
import com.woniu.internalcommon.remote.ServiceMapClient;
import com.woniu.internalcommon.request.POIRequestDTO;
import com.woniu.internalcommon.response.POIResponse;
import com.woniu.internalcommon.response.WeatherLiveResponse;
import com.woniu.internalcommon.util.TimeUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

@Component
public class MapServiceTools {
    @Autowired
    private ServiceMapClient serviceMapClient;
    @Autowired
    private RestHighLevelClient clientApi;

    @Tool(description = "POI周边搜索工具")
    public String getPOIMessage(@ToolParam(description = "用户当前的坐标 pos") String location,
                                @ToolParam (description = "POI类型") String type,
                                @ToolParam (description = "radius default 5000") Integer radius){

//        "39.990475,116.481499"
        System.out.println(location);
        System.out.println(type);
        String[] split = type.split("\\|");
        List<String> types = Arrays.stream(split).toList();
        System.out.println("---"+types);
        List<POIResponse> data = serviceMapClient.aroundPOISearch(new POIRequestDTO(location
                , radius, types)).getData();
        System.out.println(data);
        StringBuffer stringBuffer = new StringBuffer();
        for (POIResponse poiR: data){
            stringBuffer.append("name: ").append(poiR.getName()).append("\n")
                    .append("address: ").append(poiR.getAddress()).append("\n")
                    .append("distance: ").append(poiR.getDistance()).append("\n")
                    .append("location: ").append(poiR.getLocation()).append("\n")
                    .append("rating: ").append(poiR.getBusiness().getRating()).append("\n")
                    .append("type: ").append(poiR.getType()).append("\n")
                    .append("photo: ").append(poiR.getPhotos()).append("\n");

            System.out.println(stringBuffer);
        }


        return stringBuffer.toString();
    }
    @Tool (description = "当前天气查询工具")
    public String getWeather(@ToolParam(description = "城市编码 citycode") String city){
        List<?> data = serviceMapClient.getLiveWeather(city).getData();
        System.out.println(data);
        StringBuffer stringBuffer = new StringBuffer();
        for (Object  weatherR: data) {
            System.out.println(weatherR);
            WeatherLiveResponse weather = (WeatherLiveResponse) weatherR;
            stringBuffer.append(" 天气: ").append(weather.getWeather()).append("\n")
                    .append("  温度: ").append(weather.getTemperature()).append("\n")
                    .append("  风向: ").append(weather.getWindDirection()).append("\n")
                    .append("  风级: ").append(weather.getWindPower()).append("\n");
        }
        System.out.println(stringBuffer);
        return stringBuffer.toString();
    }
//    @Tool (description = "未来天气查询")
//    public String getWeather(@ToolParam()  ){
//        serviceMapClient.getForWeather("上海");
//
//        return "11";
//    }

    /**
     * 获取当前时间
     * @param timeZoneId
     * @return
     */
    @Tool(description = "获取当前时间")
    public String  getCityTimeMethod(@ToolParam(description = "Time zone id, such as Asia/Shanghai ") String timeZoneId) {
        System.out.println("The current time zone is {}"+ timeZoneId);
        timeZoneId = "Shanghai";
        return String.format("The current time zone is %s and the current time is " + "%s", timeZoneId,
                TimeUtils.getTimeByZoneId(timeZoneId));
    }
    @Tool(description = "es搜索")
    public String esSearch(@ToolParam(description = "用户的keywords") String keyword) throws IOException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 2. 构建 Match 查询 - 查询 name 字段包含"汽车"的文档
        MatchQueryBuilder matchQuery = new MatchQueryBuilder("name", keyword);
        matchQuery.fuzziness("AUTO");
        sourceBuilder.query(matchQuery);
        // 3. 构建高亮配置
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        // 设置高亮前后标签（对应JSON中的pre_tags和post_tags）
        highlightBuilder.preTags("<tag1>", "<tag2>");
        highlightBuilder.postTags("</tag1>", "</tag2>");
        // 添加name字段的高亮配置
        highlightBuilder.field(new HighlightBuilder.Field("name"));

        sourceBuilder.highlighter(highlightBuilder);

        // 4. 创建SearchRequest并设置索引
        SearchRequest request = new SearchRequest();
        request.source(sourceBuilder);
        // 假设我们要搜索的索引是"your_index_name"
        request.indices("poitype");

        // 5. 打印生成的DSL（调试用）
        System.out.println("生成的查询DSL:\n" + sourceBuilder);

        // 6. 执行查询
        SearchResponse response = clientApi.search(request, RequestOptions.DEFAULT);

        // 7. 处理结果
        System.out.println("总命中数: " + response.getHits().getTotalHits().value);

        //显示分数
        StringBuilder result = new StringBuilder();
        //只取两个结果
        int count = 0;
        for (SearchHit hit : response.getHits().getHits()) {
            if (count > 5) {
                break;
            }
            count++;
            result.append("```").append("\n")
                    .append("匹配度：").append(hit.getScore()).append("\n")
                    .append("poi类型：").append(hit.getSourceAsMap().get("name")).append("\n")
                    .append("```");
        }
//        response.getHits().forEach(h -> {
//            System.out.println("\n文档ID: " + h.getId());
//            System.out.println("文档分数: " + h.getScore());
//            System.out.println("文档内容: " + h.getSourceAsString());
//            System.out.println("高亮结果: " + h.getHighlightFields());
//        });
        return result.toString();

    }

    @Tool (description = "查询所有POI类型关键字")
    public String getAllPOITypeNames() {
        ResponseResult<List<String>> responseResult = serviceMapClient.getAllPOITypeNames();
        List<String> data = responseResult.getData();
        StringBuilder result = new StringBuilder();
        data.forEach(s -> result.append(s).append("，"));

        return result.toString();
    }


}